import { createRouter, createWebHashHistory } from "vue-router";
import { ElNotification } from "element-plus";
import { nextTick } from 'vue';
import { useViewTagsStore } from '@/store/modules/viewTagsStore'
// 引入配置文件
import config from "@/config";
//添加路由加载动画
import NProgress from "nprogress";
import "nprogress/nprogress.css";
/**
 * 引入store
 */
import { GlobalStore } from "@/store";
import { AuthStore } from "@/store/modules/auth";
/**
 * 引入配置
 */
import { LOGIN_URL } from '@/config/index';
/**
 * 引入初始化路由方法
 */
import { initDynamicRouter } from './modules/dynamicRouter'
import { staticRouter, errorRouter } from "@/router/modules/staticRouter";
const router = createRouter({
	history: createWebHashHistory(),
	routes: [...staticRouter, ...errorRouter],
});


//全局前置守卫
//to: 即将要进入的目标
//from: 当前导航正要离开的路由
//next: 一个常见的错误来源
//注意: 确保 next 在任何给定的导航守卫中都被严格调用一次
router.beforeEach(async (to, from, next) => {
	const globalStore = GlobalStore();
	// 1.加载动画
	NProgress.start();

	// 2.动态设置标题
	const title = import.meta.env.VITE_GLOB_APP_TITLE;
	document.title = to.meta.title ? `${to.meta.title} - ${title}` : title;

	// 3.判断是访问登陆页，有 Token 就在当前页面，没有 Token 重置路由并放行到登陆页
	if (to.path === LOGIN_URL) {
		if (globalStore.token) return next(from.fullPath);
		resetRouter();
		return next();
	}

	// 4.判断是否有 Token，没有重定向到 login
	if (!globalStore.token) return next({ path: LOGIN_URL, replace: true });

	// 5.如果没有菜单列表，就重新请求菜单列表并添加动态路由
	const authStore = AuthStore();
	authStore.setRouteName(to.name as string);
	if (!authStore.authMenuListGet.length) {
		await initDynamicRouter();
		return next({ ...to, replace: true });
	}
	// 6.正常访问页面
	next();
});
/**
 * @description 重置路由
 * */
export const resetRouter = () => {
	const authStore = AuthStore();
	authStore.flatMenuListGet.forEach(route => {
		const { name } = route;
		if (name && router.hasRoute(name)) router.removeRoute(name);
	});
};
router.afterEach((to, from) => {
	NProgress.done();
	var adminMain = document.querySelector('#adminui-main');
	if (!adminMain) { return false }
	nextTick(() => {
		var viewTagsStore = useViewTagsStore();
		var beforeRoute = viewTagsStore.viewTags.filter(v => v.fullPath == to.fullPath)[0]
		if (beforeRoute) {
			adminMain.scrollTop = beforeRoute.scrollTop || 0
		}
	})
});
router.onError((error) => {
	NProgress.done();
	ElNotification.error({
		title: "路由错误",
		message: error.message,
	});
});
export default router;
